import mock from "@/fake-db/mock.js"

const data = {
  products: [
    {
      "id": 1,
      "category": "wind",
      "img": "https://pixinvent.com/demo/vuexy-vuejs-admin-dashboard-template/products/09.png",
      "name": "新风系统",
      "order_status": "delivered",
      "popularity": 97,
      "location": "2-房间1",
      "price": 199.99
    },
    {
      "id": 2,
      "category": "wind",
      "img": "https://pixinvent.com/demo/vuexy-vuejs-admin-dashboard-template/products/09.png",
      "name": "空调",
      "order_status": "delivered",
      "popularity": 22,
      "location": "房间3",
      "price": 199.99
    },
    {
      "id": 3,
      "category": "wind",
      "img": "https://pixinvent.com/demo/vuexy-vuejs-admin-dashboard-template/products/09.png",
      "name": "光照",
      "order_status": "delivered",
      "popularity": 37,
      "location": "1-房间2",
      "price": 78
    },
    {
      "id": 4,
      "category": "wind",
      "img": "https://pixinvent.com/demo/vuexy-vuejs-admin-dashboard-template/products/09.png",
      "name": "新风系统",
      "order_status": "delivered",
      "popularity": 37,
      "location": "房间2",
      "price": 74
    },
    {
      "id": 5,
      "category": "wind",
      "img": "https://pixinvent.com/demo/vuexy-vuejs-admin-dashboard-template/products/09.png",
      "name": "新风系统",
      "order_status": "delivered",
      "popularity": 53,
      "location": "房间1",
      "price": 69
    },
    {
      "id": 6,
      "category": "wind",
      "img": "https://pixinvent.com/demo/vuexy-vuejs-admin-dashboard-template/products/09.png",
      "name": "新风系统",
      "order_status": "delivered",
      "popularity": 77,
      "location": "4-房间3",
      "price": 74
    },
  ]
}


mock.onGet("/api/data-list/products").reply(() => {
  return [200, JSON.parse(JSON.stringify(data.products)).reverse()];
});

// POST : Add new Item
mock.onPost("/api/data-list/products/").reply((request) => {

  // Get event from post data
  let item = JSON.parse(request.data).item

  const length = data.products.length
  let lastIndex = 0
  if(length){
    lastIndex = data.products[length - 1].id
  }
  item.id = lastIndex + 1

  data.products.push(item)

  return [201, {id: item.id}]
})

// Update Product
mock.onPost(/\/api\/data-list\/products\/\d+/).reply((request) => {

  const itemId = request.url.substring(request.url.lastIndexOf("/")+1)

  let item = data.products.find((item) => item.id == itemId)
  Object.assign(item, JSON.parse(request.data).item)

  return [200, item]
})

// DELETE: Remove Item
mock.onDelete(/\/api\/data-list\/products\/\d+/).reply((request) => {

  const itemId = request.url.substring(request.url.lastIndexOf("/")+1)

  const itemIndex = data.products.findIndex((p) => p.id == itemId)
  data.products.splice(itemIndex, 1)
  return [200]
})
